#include "decoder/subtitle_decoder_worker.hpp"
#include <iostream>
#include <nlohmann/json.hpp>
#include <iomanip> 
#include "common/utils.hpp"

namespace WD {

using json = nlohmann::json;

SubtitleDecoderWorker::SubtitleDecoderWorker(
    int stream_index,
    AVFormatContext* fmt_ctx,
    std::shared_ptr<ThreadSafeQueue<AVPacket*>> pkt_queue,
    std::function<void(const SubtitleInfo&)> subtitle_cb)
    : stream_index_(stream_index),
      fmt_ctx_(fmt_ctx),
      pkt_queue_(std::move(pkt_queue)),
      subtitle_cb_(std::move(subtitle_cb)) {}

SubtitleDecoderWorker::~SubtitleDecoderWorker() {
    
}

void SubtitleDecoderWorker::start() {
    running_ = true;
    thread_ = std::thread(&SubtitleDecoderWorker::decodeLoop, this);
}

void SubtitleDecoderWorker::stop() {
    running_ = false;
    if (thread_.joinable()) thread_.join();
}
// static int64_t last_pts = -1;
void SubtitleDecoderWorker::decodeLoop() {
    while (running_) {
        double now_utc = std::chrono::duration<double>(
            std::chrono::system_clock::now().time_since_epoch()).count();
        AVPacket* pkt = nullptr;
        if (!pkt_queue_->pop(pkt, running_)) break;

        if (pkt->stream_index != stream_index_) {
            av_packet_unref(pkt);
            av_packet_free(&pkt);
            continue;
        }

        std::string json_str(reinterpret_cast<char*>(pkt->data), pkt->size);
        std::cerr << "[DEBUG] Sub JSON: " << json_str << std::endl;


        try {
            SubtitleInfo info = parseJsonSubtitle(json_str);

            // // 打印当前 pkt->pts 和是否回流检测
            // std::cout << "[SubtitleDecoderWorker] pkt->pts: " << pkt->pts;
            // if (last_pts != -1 && pkt->pts < last_pts) {
            //     std::cout << "  <-- pts回流，前一帧 pts=" << last_pts;
            // }
            // std::cout << std::endl;

            // last_pts = pkt->pts;

            // 计算图像 UTC 时间戳（秒）
            // double base_time_sec = WD::utils::parseUtcToSec(info.datetime);  // 如："2025-06-25T09:51:02.00000" -> 1756147862.0
            // double delta_us = static_cast<double>(info.timestamp) - static_cast<double>(info.pps_timestamp);
            // double image_time_utc = base_time_sec + 1.0 + delta_us / 1e6;

            double image_time_utc = 0.0;

            if (!info.datetime.empty()) {
                // 有 datetime，正常解析
                double base_time_sec = WD::utils::parseUtcToSec(info.datetime);
                double delta_us = static_cast<double>(info.timestamp) - static_cast<double>(info.pps_timestamp);
                image_time_utc = base_time_sec + 1.0 + delta_us / 1e6;

                // 保存当前帧的时间信息
                last_valid_image_utc_ = image_time_utc; 
                last_valid_timestamp_ = info.timestamp;

                // std::cerr << "[SubtitleDecoderWorker] image_time_utc: " << std::fixed << std::setprecision(6) << image_time_utc
                //     << " (base_time_sec=" << base_time_sec
                //     << ", timestamp=" << info.timestamp
                //     << ", pps_timestamp=" << info.pps_timestamp << ")\n";

            } else if (last_valid_image_utc_ != 0) {
                // 无 datetime，尝试根据 timestamp 插值
                int64_t delta_ts = static_cast<double>(info.timestamp) - static_cast<double>(info.pps_timestamp);
                image_time_utc = last_valid_image_utc_  + delta_ts / 1e6;

                // std::cerr << "[WARN] Missing datetime, interpolated UTC = "
                //           << std::fixed << std::setprecision(6) << image_time_utc << "\n";

                last_valid_image_utc_ = image_time_utc;

            } else {
                image_time_utc = now_utc;

                // std::cerr << "[WARN] Missing datetime and no valid timestamp, fallback to now = "
                //         << std::fixed << std::setprecision(6) << image_time_utc << "\n";

                last_valid_image_utc_ = image_time_utc;
                last_valid_timestamp_ = info.timestamp;  // 虽然 datetime 缺失，但可以保存 timestamp
            }
            WD::SubtitleSyncManager::instance().insert(pkt->pts, image_time_utc);
        } catch (const std::exception& e) {
            std::cerr << "[SubtitleDecoderWorker] JSON parse error: " << e.what() << "\n";
        }

        av_packet_unref(pkt);
        av_packet_free(&pkt);
    }
}

SubtitleInfo SubtitleDecoderWorker::parseJsonSubtitle(const std::string& json_str) {
    json j = json::parse(json_str);
    SubtitleInfo info;

    info.seq = j.value("seq", -1);

    // 提取 image_info
    const auto& img = j.at("image_info");
    info.timestamp = img.at("timestamp").get<uint64_t>();
    info.exposure_time = img.at("exposure_time").get<int>();
    info.scan_time = img.at("scan_time").get<int>();

    // gps_info 和 pps_info 是可选字段
    if (j.contains("gps_info")) {
        const auto& gps = j["gps_info"];
        info.gps_timestamp = gps.at("timestamp").get<uint64_t>();
        info.datetime = gps.value("datetime", "");
    }else {
        info.gps_timestamp = 0;
        info.datetime = "";
    }

    if (j.contains("pps_info")) {
        const auto& pps = j["pps_info"];
        info.pps_timestamp = pps.at("timestamp").get<uint64_t>();
    }else {
        info.pps_timestamp = 0;
    }

    return info;
}


} // namespace WD
